package com.dbh.company.util;

import cn.hutool.core.lang.Console;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * pdfUtil
 * @author dongbanghui
 * @create 2023/2/15
 */
public class PdfUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PdfUtil.class);

    /**
     * currentDpi/newDpi
     */
    public static final float FACTOR = 0.7f;

    public static void compress(byte[] source, String target) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(source);
        int n = reader.getXrefSize();
        PdfObject object;
        PRStream stream;
        // Look for image and manipulate image stream
        for (int i = 0; i < n; i++) {
            object = reader.getPdfObject(i);
            if (object == null || !object.isStream())
                continue;
            stream = (PRStream)object;
            if (!PdfName.IMAGE.equals(stream.getAsName(PdfName.SUBTYPE)))
                continue;
            if (!PdfName.DCTDECODE.equals(stream.getAsName(PdfName.FILTER)))
                continue;
            PdfImageObject image = new PdfImageObject(stream);
            BufferedImage bi = image.getBufferedImage();
            if (bi == null)
                continue;
            int width = (int)(bi.getWidth() * FACTOR);
            int height = (int)(bi.getHeight() * FACTOR);
            if (width <= 0 || height <= 0)
                continue;
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
            Graphics2D g = img.createGraphics();
            g.drawRenderedImage(bi, at);
            ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
            ImageIO.write(img, "JPG", imgBytes);
            stream.clear();
            stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
            stream.put(PdfName.TYPE, PdfName.XOBJECT);
            stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
            stream.put(PdfName.FILTER, PdfName.DCTDECODE);
            stream.put(PdfName.WIDTH, new PdfNumber(width));
            stream.put(PdfName.HEIGHT, new PdfNumber(height));
            stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
            stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
        }
        reader.removeUnusedObjects();
        // Save altered PDF
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));
        stamper.setFullCompression();
        stamper.close();
        reader.close();
    }

    public static Integer countText(String url) throws IOException {
        PdfReader reader = new PdfReader(url);
        int n = reader.getNumberOfPages();
        int characterCount = 0;
        for (int i = 1; i <= n; i++) {
            String contentOfPage  = PdfTextExtractor.getTextFromPage(reader, i);
            contentOfPage = contentOfPage.replaceAll("\\p{C}", "").replaceAll(" ", "");
            characterCount += contentOfPage.length();
            LOG.info("第{}页,字数为:{}", i, contentOfPage.length());
            Console.log("第{}页,字数为:{}", i, contentOfPage.length());
        }
        LOG.info("文档总页数为:{},总字数为:{},", n, characterCount);
        Console.log("文档总页数为:{},总字数为:{},", n, characterCount);
        return characterCount;
    }

    public static void main(String[] args) throws IOException, DocumentException {
        String url = "http://storage.lianjia.com/xieyi-freeform-file/supplier_electronic_contract/pdf/cform/011bfe3e-cddb-4ae8-a63b-39eef6da0d04.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230216T021308Z&X-Amz-SignedHeaders=host&X-Amz-Expires=35999&X-Amz-Credential=8VPUGUB18M0AC6B5MNXX%2F20230216%2Fcn-north-1%2Fs3%2Faws4_request&X-Amz-Signature=44adbdb6d1630bfc49a0e4ccc8584888eaacd5167ad7651f722a4b4c897354a8";
        Integer countText = countText(url);
        System.out.println(countText);
    }

}
